package com.stylefeng.web.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.common.controller.BaseController;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.util.IpGetter;
import com.stylefeng.guns.core.util.PasswordEncoder;
import com.stylefeng.guns.modular.shop.service.*;
import com.stylefeng.web.utils.MemberUtils;
import com.stylefeng.guns.persistence.shop.model.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author stylefeng
 * @since 2017-05-17
 */
@Controller
@RequestMapping("front")
public class IndexController extends BaseController {
    private String PREFIX = "/web/";

    @Resource
    ITArticleService itLinkService;

    @Resource
    ITGoodsService itGoodsService;
    @Resource
    ITStoreService itStoreService;
    @Resource
    ITBrandService itBrandService;
    @Resource
    ITMemberService itMemberService;
    /**
     * 跳转到部门管理首页
     */
    @RequestMapping("index")
    public String index() {
        return PREFIX + "index.html";
    }


    /**
     * 跳转到商品详情
     */
    @RequestMapping("/goodsDetail/{id}")
    public String goodsDetail(@PathVariable Long id, Model model) {
        TGoods goods = itGoodsService.selectById(id);
        model.addAttribute("goods",goods);
        if(goods.getImgmore()!=null && goods.getImgmore().indexOf(",")>-1){
            model.addAttribute("imgs", goods.getImgmore().split(","));
        }
        goods.setClickHit(goods.getClickHit()+1);
        itGoodsService.updateById(goods);
        TStore store = itStoreService.selectById(goods.getStoreid());
        model.addAttribute("store",store);
        LogObjectHolder.me().set(goods);
        return PREFIX + "goodsDetail.html";
    }
    /**
     * 跳转到店铺详情
     */
    @RequestMapping("/store/{id}")
    public String store(@PathVariable Long id, Model model) {
        TStore store = itStoreService.selectById(id);
        model.addAttribute("store",store);
        LogObjectHolder.me().set(store);
        return PREFIX + "store.html";
    }

    /**
     * 根据品牌查询商品
     */
    @RequestMapping("/brand/{id}")
    public String brand(@PathVariable Long id, Model model) {
        List<TGoods> goodsList = itGoodsService.getGoodsByBrandid(id);
        model.addAttribute("goodsList",goodsList);
        LogObjectHolder.me().set(goodsList);
        return PREFIX + "list.html";
    }

    /**
     * 通过菜单类别
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping("/goodsListBygcId/{gcId}")
    public String goodsListBygcId(@PathVariable("gcId") Long gcId, Model model)throws Exception{
        ModelAndView mav=new ModelAndView();
        TGoods g=new TGoods();
        g.setClassid(gcId);
        Page<TGoods> page=itGoodsService.selectgoodsListByType(1, 40, g);
        model.addAttribute("page",page);
        return PREFIX + "list.html";
    }












    /**
     * 跳转到登录页面
     *
     * @return
     */
    @RequestMapping(value = "tlogin", method = RequestMethod.GET)
    public String toLogin() {
        if( MemberUtils.getSessionLoginUser() != null){
            return "redirect:/index";
        }
        return PREFIX + "login.html";
    }

    /**
     * 登录验证
     *
     * @param username
     * @param password
     * @param
     * @return
     */
    @RequestMapping(value = "tlogin", method = RequestMethod.POST)
    public @ResponseBody Map<String, Object> checkLogin(String username,
                                                        String password,  HttpServletRequest request) {

        Map<String, Object> msg = new HashMap<String, Object>();
        HttpSession session = request.getSession();
        //code = StringUtils.trim(code);
        username = StringUtils.trim(username);
        password = StringUtils.trim(password);
        //Object scode = session.getAttribute("code");
        String sessionCode = null;
//			if (scode != null)
//				sessionCode = scode.toString();
//			if (!StringUtils.equalsIgnoreCase(code, sessionCode)) {
//				msg.put("error", "验证码错误");
//				return msg;
//			}
        TMember user = itMemberService.checkUser(username, password);
        if (null != user) {
            session.setAttribute(MemberUtils.SESSION_LOGIN_MEMBER, user);
        } else {
            msg.put("error", "用户名或密码错误");
        }
        return msg;
    }

    /**
     * 跳转到登录页面
     *
     * @return
     */
    @RequestMapping(value = "treg", method = RequestMethod.GET)
    public String reg() {
        if( MemberUtils.getSessionLoginUser() != null){
            return "redirect:/index";
        }
        return PREFIX + "register.html";
    }

    @RequestMapping(value = "treg", method = RequestMethod.POST)
    public @ResponseBody Map<String, Object> reg(
            @RequestParam(value = "password",required=true)String  password,
            @RequestParam(value = "email",required=false)String email,
            @RequestParam(value = "username",required=false)String username,
            @RequestParam(value = "phone",required=false)String phone,
            @RequestParam(value = "passwordRepeat",required=true)String passwordRepeat,HttpServletRequest request) {
        Map<String, Object> msg = new HashMap<String, Object>();
        if (!StringUtils.equalsIgnoreCase(password, passwordRepeat)) {
            msg.put("error", "密码不一致!");
            return msg;
        }
        String secPwd = null ;

        TMember m=new TMember();
        m.setEmail(email);
        m.setUsername(username);
        secPwd = PasswordEncoder.encrypt(password, username);
        m.setPhone(phone);
        m.setStatus(1);
        m.setAddress(IpGetter.getLocalIP());
        m.setPassword(secPwd);
        Random r = new Random();
        m.setGold(r.nextInt(10));
        m.setAddtime(new Date());
        m.setTrueName(m.getUsername());
        try {
            boolean result = itMemberService.insert(m);
            HttpSession session = request.getSession();
            if (result) {
                TMember mb=new TMember();
                mb.setUsername(username);
                mb.setPassword(secPwd);
                session.setAttribute(MemberUtils.SESSION_LOGIN_MEMBER, itMemberService.selectOne(new EntityWrapper<>(mb)));
            } else {
                msg.put("error", "注册失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return msg;
    }
    /**
     * 用户退出
     *
     * @return 跳转到登录页面
     */
    @RequestMapping("tlogout")
    public String logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return "redirect:/front/tlogin";
    }

    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public String uploadFileHandlerStore(@RequestParam("file") MultipartFile file,
                                     HttpServletRequest request) throws IOException {
        return fileUpload(file, request,"upload/store/");
    }

    @RequestMapping(value = "/fileUpload1", method = RequestMethod.POST)
    @ResponseBody
    public String uploadFileHandlerGoods(@RequestParam("file") MultipartFile file,
                                    HttpServletRequest request) throws IOException {
        return fileUpload(file, request,"upload/project/");
    }

    private String fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request,String path) throws IOException {
        if (!file.isEmpty()) {
            InputStream in = null;
            OutputStream out = null;
            try {
                String filePath = request.getSession().getServletContext().getRealPath("/") +path ;
                File dir = new File(filePath);
                if (!dir.exists())
                    dir.mkdirs();
                File serverFile = new File(dir.getAbsolutePath() + File.separator + file.getOriginalFilename());
                in = file.getInputStream();
                out = new FileOutputStream(serverFile);
                byte[] b = new byte[1024];
                int len = 0;
                while ((len = in.read(b)) > 0) {
                    out.write(b, 0, len);
                }
                System.out.println("file:"+serverFile);
                out.close();
                in.close();
                return file.getOriginalFilename();

            } catch (Exception e) {
                return file.getOriginalFilename();
            } finally {
                if (out != null) {
                    out.close();
                    out = null;
                }

                if (in != null) {
                    in.close();
                    in = null;
                }
            }
        } else {
            return file.getOriginalFilename();
        }
    }
}
